<?php

namespace Admin\Controller;

class AdController extends AdminController {

    public function index() {
        $field = "*";
        $order = "create_time";

        $M = M('Ad');

        $list = $this->lists($M, '', $order, $field);


        $this->assign('_list', $list);
        $this->meta_title = '首页广告管理';
        $this->display();
    }

    public function add() {
        $id = I('id', 0, 'intval');
        if (IS_POST) {

            $data['ad_title'] = I('ad_title');
            $data['ad_img'] = I("ad_img");

            if (empty($data['ad_title'])) {
                $this->error('请输入广告标题!');
                exit;
            }

            if (empty($data['ad_img'])) {
                $this->error('请上传广告图!');
                exit;
            }

            $data['ad_content'] = I("ad_content");

            $data['start_time'] = I("start_time");
            $data['end_time'] = I("end_time");

            if ($data['end_time'] && $data['start_time']) {
                if ($data['end_time'] <= $data['start_time']) {
                    $this->error('开始时间不允许小于等于结束时间');
                    exit;
                }
            }

            if (empty($data['start_time'])) {
                $this->error('请选择开始时间!');
            }

            if (empty($data['end_time'])) {
                $this->error('请选择结束时间!');
            }



            if ($id == 0) {
                $res = M('Ad')->add($data);
            } else {
                $res = M('Ad')->where(array('ad_id' => $id))->save($data);
            }

            $this->success('操作成功', U('index'));

//            if ($res) {
//                $this->success('操作成功', U('index'));
//            } else {
//                $this->error('操作失败');
//            }
        } else {
            $data = M('Ad')->where(['ad_id' => $id])->find();

            $this->assign('data', $data);
            $this->display();
        }
    }

    public function del() {
        $id = I('id', 0, 'intval');

        $res = M('Ad')->where(['ad_id' => $id])->delete();

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

}
